package com.k.kppcloud.consumer.controller;

import com.k.kppcloud.modules.sdk.feign.admin.UserControllerFeign;
import com.k.kppcloud.modules.sdk.feign.admin.domain.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/consumer")
public class ConsumerAdminController {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ConsumerAdminController.class);
    @Autowired
    private UserControllerFeign userControllerFeign;

    @RequestMapping("/sdk/admin/user/list")
    @ResponseBody
    public List<UserDTO> adminUserList() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        // 同步调用
        List<UserDTO> list = feignRemoteCall();

        // 异步调用需要设置，拦截器才可以设置到 header 信息, 否则设置不到
        feignRemoteCallAsync(attributes);
        return list;
    }

    private List<UserDTO> feignRemoteCall(){
        return userControllerFeign.list();
    }
    private void feignRemoteCallAsync(RequestAttributes attributes){
        RequestContextHolder.setRequestAttributes(attributes);
        CompletableFuture.runAsync(() -> {
            // 因为异步线程需要新的线程，而新的线程里没有request数据，所以我们自己设置进去
            RequestContextHolder.setRequestAttributes(attributes);
            try {
                // 远程调用
            } catch (Exception e) {
                log.warn("\n远程调用会员服务失败 [会员服务可能未启动]");
            }
        }, null);
    }
}
